import sys
sys.path.append("../")

from model.CommonDb import *
from model.ExamModel import *
from frameworks.utils.RedisUtil import *
import datetime

class ExamPaperController:
    def __init__(self,args):
        self.args = args
        self.model = ExamModel()
        self.redis = RedisUtil()

    def run(self):
        if self.args["func"] == "getExamPaper":
            return self.getExamPaper(self.args["sid"])
        elif self.args["func"] == "addUserExamPaper":
            return self.addUserExamPaper(self.args["params"],self.args["userid"],self.args["endtime"])
        elif self.args["func"] == "addUserMustExamPaper":
            return self.addUserMustExamPaper(self.args["params"],self.args["userid"],self.args["endtime"])
        elif self.args["func"] == "addMustExamRecord":
            return self.addMustExamRecord(self.args["sid"],self.args["erid"],self.args["userid"])
        elif self.args["func"] == "getRandomQuestion":
            return self.getRandomQuestion()
        elif self.args["func"] == "getBatchQuestion":
            return self.getBatchQuestion(self.args["data"])

    def getExamPaper(self,sid):
        rs = self.model.getExamPaper(sid)
        total = []
        lastBig = 0
        bigcnt = 0
        smallcnt = 0
        # 提取大题目的汇总信息
        options = {}
        for row in rs:
            if row["big_ord"] == lastBig:
                options["main_str_" + str(row["big_ord"])]["count"] += 1
                options["main_str_" + str(row["big_ord"])]["all_score"] += int(row["score"])
            else:
                lastBig = row["big_ord"]
                options["main_str_" + str(row["big_ord"])] = {"big_ord": row["big_ord"], "count": 1,
                                                              "title": row["qtype"], "all_score": int(row["score"]),
                                                              "child": []}
        # 生成小题目的信息
        allrs = []
        for key in options.keys():
            option_data = []
            for row in rs:
                if row["qtype"] == options[key]["title"]:
                    li_order = "qu_" + str(int(row["big_ord"]) - 1) + "_" + str(int(row["small_ord"]) - 1)
                    question_options = row["content"].split("|||")
                    contents = []
                    n = 0
                    for question_option in question_options:
                        question_option_childe = question_option.split("||")
                        css_str = str(int(row["big_ord"]) - 1) + "_answer_" + str(
                            int(row["small_ord"]) - 1) + "_option_" + str(n + 1)
                        contents.append(
                            {
                                "css": css_str,
                                "ordername": question_option_childe[0],
                                "title": question_option_childe[1]
                            }
                        )
                        n += 1
                    rowoption = {
                        "id": row["qid"],
                        "orderkey": int(row["small_ord"]),
                        "li_order": li_order,
                        "score": int(row["score"]),
                        "title": row["title"],
                        "content": contents,
                        "answer": row["answer"],
                        "other_comment": row["other_comment"]
                    }
                    option_data.append(rowoption)
            options[key]["child"] = option_data
            allrs.append(options[key])
        return allrs

    def addUserExamPaper(self,params,userid,endtime):
        final_score = 0
        db = CommonDb("user_answer")
        for key in params.keys():
            if key.find("qu_") == 0:
                if "".join(params[key]) == params["answer_" + key][0]:
                    final_score += int(params["score_" + key][0])
                    unit_score = int(params["score_" + key][0])
                else:
                    unit_score = 0
                if params["paper_type"][0] != "自动组题":
                    info = {
                        "erid": params["erid"][0],
                        "uid": userid,
                        "sid": params["sid"][0],
                        "qid": params["score_" + key][0],
                        "answer": "".join(params[key]),
                        "score": unit_score
                    }
                    db.add(info, True, True)
        if params["paper_type"][0] != "自动组题":
            db = CommonDb("exam_record")
            info = {
                "erid": params["erid"][0],
                "uid": userid,
                "sid": params["sid"][0],
                "starttime": self.redis.vget(params["erid"][0]+str(userid)),
                "endtime": endtime,
                "score": final_score
            }
            db.add(info,True,True)
        return final_score

    def addUserMustExamPaper(self,params,userid,endtime):
        final_score = 0
        db = CommonDb("user_answer")
        for key in params.keys():
            if key.find("qu_") == 0:
                if "".join(params[key]) == params["answer_" + key][0]:
                    final_score += int(params["score_" + key][0])
                    unit_score = int(params["score_" + key][0])
                else:
                    unit_score = 0

                info = {
                    "erid": params["erid"][0],
                    "uid": userid,
                    "sid": params["sid"][0],
                    "qid": params["score_" + key][0],
                    "answer": "".join(params[key]),
                    "score": unit_score
                }
                db.add(info, True, True)

        db = CommonDb("exam_record")
        info = {
            "endtime": endtime,
            "score": final_score
        }
        db.update(info, "id=" + params["ertid"][0])
        return final_score

    def addMustExamRecord(self, sid, erid, userid):
        db = CommonDb("exam_record")
        info = {
            "erid": erid,
            "uid": userid,
            "sid": sid,
            "starttime": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        }
        return db.add(info, True, True)

    def getRandomQuestion(self):
        conf = [
            {"type": "单选题", "count": 60, "all_score": 60, "per_score": 1},
            {"type": "判断题", "count": 40, "all_score": 40, "per_score": 1},
        ]
        total = []
        lastBig = 0
        bigcnt = 0
        smallcnt = 0
        options = []
        # 提取大题目的汇总信息
        n = 1
        for unitConf in conf:
            rs = self.model.getRandomPaper(unitConf["type"],unitConf["count"])
            options.append(
                {
                    "title": unitConf["type"],
                    "count": unitConf["count"],
                    "all_score": unitConf["all_score"],
                    "child": []
                }
            )
            m = 0
            for row in rs:
                li_order = "qu_" + str(n-1) + "_" + str(m)
                question_options = row["content"].split("|||")
                contents = []
                t = 0
                for question_option in question_options:
                    question_option_childe = question_option.split("||")
                    css_str = str(n - 1) + "_answer_" + str(m) + "_option_" + str(t + 1)
                    contents.append(
                        {
                            "css": css_str,
                            "ordername": question_option_childe[0],
                            "title": question_option_childe[1]
                        }
                    )
                    t += 1
                if row["other_comment"].find(".jpg") > 0 or row["other_comment"].find(".png") > 0:
                    rmi = row["other_comment"]
                else:
                    rmi = ""

                rowoption = {
                    "id": row["qid"],
                    "orderkey": int(m)+1,
                    "li_order": li_order,
                    "score": int(unitConf["per_score"]),
                    "title": row["title"],
                    "content": contents,
                    "answer": row["answer"],
                    "other_comment": rmi
                }
                print(rowoption)
                options[n-1]["child"].append(rowoption)
                m += 1
            n += 1
        return options

    def getBatchQuestion(self,data):
        rs = self.model.getAllQuestions("questions_jiashizheng_" + data["question_group_name"])
        print(len(rs))
        if len(rs) % int(data["per_page"]) == 0:
            size = len(rs) / int(data["per_page"])
        else:
            size = int(len(rs) / int(data["per_page"])) + 1
        print(size)
        db = CommonDb("questions_jiashizheng_" + data["question_group_name"])
        db1 = CommonDb("exam_paper")
        for i in range(0,size):
            print(i)
            sid = str(data["sid"]) + str(10 + i)
            info = {
                "question_group_id": data["question_group_id"],
                "question_group_name": data["question_group_name"],
                "sid": sid,
                "paper_type": data["paper_type"],
                "name": data["name"]+str(i+1),
                "creator": data["creator"],
                "other_comment": data["other_comment"]
            }
            db1.add(info,True)
            pagers = db.getPageData("*","1",i+1,int(data["per_page"]),"qtype,id","")
            db3 = CommonDb("exam_paper_question")
            big_ord = 0
            small_org = 0
            qtype = ""
            for line in pagers["data"]:
                if line["qtype"] != qtype:
                    big_ord += 1
                    small_org = 1
                    qtype = line["qtype"]
                newinfo = {
                    "sid": sid,
                    "qid": line["qid"],
                    "big_ord": big_ord,
                    "small_ord": small_org,
                    "score":0
                }
                db3.add(newinfo,True)
                small_org += 1




